package dyyx.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;




public class CommUtil{
	
	public static final String LINE = "\n";
	public static final String BLANK_SPACE = " ";
	public static final String UNDERLINE = "_";


	private static final String UTF8 = "utf8";
	//private static final String CONF = "/conf.properties";

	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String YES = "Y";
    public static final String NO = "N";
    
    public static final String PRE_TAG_START = "<pre>";
    public static final String PRE_TAG_END = "</pre>";
    
    
    public static final int PRE_TAG_START_LEN = PRE_TAG_START.length();
    public static final int PRE_TAG_END_LEN = PRE_TAG_END.length();
    
    private static final Random rand = new Random();


	public static void main(String[] args) throws Exception {
		System.out.println("CommUtil "+System.currentTimeMillis());
		String str = "<pre>123</pre>";
		String str2 = getResult(str);
		System.out.println(str);
		System.out.println(str2);

	}
	
	
	public static String getErrorMsg(Throwable e){
		if(e==null){
			return null;
		}
		StringBuilder sb = new StringBuilder();
		
		while(true){
			sb.append(e).append("\n");
			e = e.getCause();
			if(e==null){
				break;
			}
		}
		
		return sb.toString();
	}
	
	public static String getTimeStr(long time){
		if(time<=0){
			return "NULL";
		}
		return getDateString(new Date(time));
	}
	
	public static List<Double> getDoubleList(List<String> list){
		if(list==null || list.isEmpty()){
			return null;
		}
		Double v = null;
		List<Double> list2 = new ArrayList<Double>();
		for(String item:list){
			v = getDoubleObj(item);
			if(v!=null && v>0){
				list2.add(v);
			}
		}
		return list2;
	}
	
	public static double[] toDoubleArr(List<Double> list){
		if(list==null || list.isEmpty()){
			return null;
		}
		int num = list.size();
		
		double[] arr = new double[num];
		Double obj = null;
		for(int i=0;i<num;i++){
			obj = list.get(i);
			if(obj!=null){
				arr[i] = obj.doubleValue();
			}
		}
		return arr;
	}
	
	public static List<String> getList(String str){
		return getList(str,CommConst.COMM);
	}

	
	public static List<String> getList(String str,String sep){
		if(str==null){
			return null;
		}
		if(sep==null || sep.length()<=0){
			sep = CommConst.COMM;
		}
		String[]arr = StringUtils.split(str, sep);
		if(arr==null || arr.length<=0){
			return null;
		}
		List<String> list = new ArrayList<String>();
		for(String item:arr){
			if(StringUtils.isBlank(item)){
				continue;
			}
			item = item.trim();
			list.add(item);
		}
		return list;
	}
	
	public static boolean isBlank(String str){
		return StringUtils.isBlank(str);
	}


	public static void doSleep(long time){
		try{
			if(time<=0){
				return;
			}
			Thread.sleep(time);
		}catch(Throwable e){

		}
	}


	public static byte[] readBytesFromResource(String name) throws Exception {
		InputStream is = null;
		try {
			is = CommUtil.class.getResourceAsStream(name);
			
			//is = CommUtil.class.getClassLoader().getResourceAsStream(name);
			
			if(is==null){
				is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
			}
			
			if (is == null) {
				throw new Exception("resource not find,name=" + name);
			}
			return toBytes(is);
		} finally {
			close(is);
		}
	}



    public static byte[] readBytes(String file) throws Exception {
		InputStream is = null;
		try {
			is = new FileInputStream(new File(file));
            return toBytes(is);
		} finally {
			close(is);
		}
	}

    public static String read(String file,String charset) throws Exception {
    	byte[] bytes = readBytes(file);
		if(bytes==null || bytes.length<=0){
			return null;
		}
		if(charset==null){
			charset = UTF8;
		}
		return new String(bytes,charset);
	}

    private static byte[] toBytes(InputStream is)throws Exception{
    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	int tmp = 0;
    	while((tmp=is.read())!=-1){
    		bos.write(tmp);
    	}
    	return bos.toByteArray();
    }

    public static void close(Closeable obj) {
		if (obj == null) {
			return;
		}
		try {
			obj.close();
		} catch (Throwable e) {

		}
	}


    public static int size(List list){
    	if(list==null){
    		return -1;
    	}
    	return list.size();
    }

    public static boolean empty(List list){
    	if(list==null || list.isEmpty()){
    		return true;
    	}
    	return false;
    }


    public static String getDataString(Map<String,String> map){
    	if(map==null || map.isEmpty()){
    		return null;
    	}
    	Set<Map.Entry<String, String>> entrys = map.entrySet();
    	String key = null;
    	String value = null;
    	StringBuilder sb = new StringBuilder();
    	boolean first = true;
    	for(Map.Entry<String, String> item:entrys){
    		key = item.getKey();
    		value = item.getValue();
    		if(StringUtils.isBlank(key) || StringUtils.isBlank(value)){
    			continue;
    		}
    		key = key.trim();
    		value = value.trim();

    		if(first){
    			first = false;
    		}else{
    			sb.append(CommConst.COMM);
    		}
    		sb.append(key).append(CommConst.EQ).append(value);
    	}

    	return sb.toString();
    }

    public static Map<String,String> getDataMap(String str){
    	if(StringUtils.isBlank(str)){
    		return null;
    	}
    	String[]arr = StringUtils.split(str, CommConst.COMM);
    	if(arr==null||arr.length<=0){
    		return null;
    	}
    	Map<String,String> map = new HashMap<String,String>();
    	for(String item:arr){
    		if(StringUtils.isBlank(item)){
    			continue;
    		}
    		buildDataValue(item,map);
    	}

    	return map;
    }

    private static void buildDataValue(String str,Map<String,String> map){
    	int pos = str.indexOf(CommConst.EQ);
    	if(pos<=0){
    		return;
    	}
    	String key = str.substring(0, pos);
    	if(StringUtils.isBlank(key)){
    		return;
    	}
    	String value = str.substring(pos+1);
    	if(StringUtils.isBlank(value)){
    		return;
    	}
    	key = key.trim();
		value = value.trim();
    	map.put(key, value);
    }


    public static BufferedReader createBufferedReader(String file,String charset)throws Exception{
    	if(StringUtils.isBlank(charset)){
    		charset = CommConst.UTF8;
    	}

    	BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),charset));

    	return br;
    }

    public static String readFirstLine(BufferedReader br,boolean ignoreBlank)throws Exception{
    	String line = null;
    	while((line=br.readLine())!=null){

    		if(ignoreBlank && StringUtils.isBlank(line)){
    			continue;
    		}

    		return line;
    	}
    	return null;
    }

	public static String readFirstLine(String file, String charset, boolean ignoreBlank) throws Exception {

		BufferedReader br = null;
		try {
			br = createBufferedReader(file, charset);
			return readFirstLine(br, ignoreBlank);
		} finally {
			close(br);
		}

	}


    public static long getLong(String str){
    	try{
    		return Long.parseLong(str);
    	}catch(Throwable e){
    		return 0;
    	}
    }
    

    public static int getInt(String str){
    	try{
    		return Integer.parseInt(str);
    	}catch(Throwable e){
    		return 0;
    	}
    }


    public static double getDouble(String str){
    	try{
    		return Double.parseDouble(str);
    	}catch(Throwable e){
    		return 0.0;
    	}
    }
    

    public static Double getDoubleObj(String str){
    	try{
    		return Double.parseDouble(str);
    	}catch(Throwable e){
    		return null;
    	}
    }

	public static String getDateString(Date date, String format) {
		if (date == null) {
			return null;
		}
		if (StringUtils.isBlank(format)) {
			format = DATE_FORMAT;
		}
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		} catch (Throwable e) {
			return date.toString();
		}
	}

	public static String getDateString(Date date) {
		return getDateString(date, null);
	}

	public static String getNowDateString() {
		return getDateString(new Date(), null);
	}
	
	public static Map<String,String> getArgsMap(String[]args){
		if(args==null || args.length<=0){
			return null;
		}
		int pos = 0;
		String key = null;
		String value = null;
		Map<String,String> map = new HashMap<String,String>();
		for(String item:args){
			if(StringUtils.isBlank(item)){
				continue;
			}
			item = item.trim();
			pos = item.indexOf(CommConst.EQ);
			if(pos<=0){
				continue;
			}
			key = item.substring(0, pos);
			value = item.substring(pos+1);
			if(StringUtils.isBlank(key) || StringUtils.isBlank(value)){
				continue;
			}
			key = key.trim();
			value = value.trim();
			map.put(key, value);
	
		}
		
		return map;
	}
	
	public static Map<String,String> getArgsMap(String str){
		
		return getArgsMap(StringUtils.split(str, CommConst.BLANK));
	}
	

	public static int getInt(Map<String,String> map,String key){		
		if(map==null || StringUtils.isBlank(key)){
			return 0;
		}
		return getInt(map.get(key));
	}
	
	public static long getLong(Map<String,String> map,String key){		
		if(map==null || StringUtils.isBlank(key)){
			return 0;
		}
		return getLong(map.get(key));
	}
	
	public static String get(Map<String,String> map,String key){		
		if(map==null || StringUtils.isBlank(key)){
			return null;
		}
		return map.get(key);
	}
	
    public static int strlen(Object o){
    	if(o==null){
    		return -1;
    	}
    	return o.toString().length();
    }
    
    
    public static PropertiesResult readProperties(String resource) {
        if (resource == null) {
            return null;
        }
        PropertiesResult result = new PropertiesResult();

        Properties prop = new Properties();
        URL u = CommUtil.class.getResource(resource);
        if (u == null) {
        	result.type=1;
            u = Thread.currentThread().getContextClassLoader().getResource(resource);
        }
        InputStream inStream = null;
        try {
            if (u != null) {
                inStream = u.openStream();
            }
            if (inStream == null) {
                throw new RuntimeException("resource not exist," + resource);
            }
            prop.load(inStream);
            
            
            result.name = resource;
            result.properties = prop;
            result.url = u;
            
            return result;
        } catch (Throwable e) {
            throw new RuntimeException("readProperties error", e);
        } finally {
            close(inStream);
        }
    }
    
    public static String getResult(String str){
    	if(StringUtils.isBlank(str)){
    		return null;
    	}
    	str = str.trim();
    	
    	if(str.startsWith(PRE_TAG_START)){
    		str = str.substring(PRE_TAG_START_LEN);
    	}
    	//System.out.println("***"+str);
    	
    	if(str.endsWith(PRE_TAG_END)){
    		str = str.substring(0,str.length() -1 - PRE_TAG_END_LEN);
    	}
    	
    	return str;
    }
    
    
    public static int getNextInt(int min,int max){
    	if(min>=max){
    		return 0;
    	}
    	int dif = max - min;
    	return min + rand.nextInt(dif);
    }
    
    public static double getNextDouble(double min,double max){
    	if(min>=max){
    		return 0;
    	}
    	double dif = max - min;
    	//return min + rand.nextInt(dif);
    	return min + rand.nextDouble() * dif;
    }
    
    public static long getNextLong(long min,long max){
    	if(min>=max){
    		return 0;
    	}
    	return (long)getNextDouble(min,max);
    }
    
    
    public static String toJsonString(Object obj){
    	if(obj==null){
    		return null;
    	}
    	return JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.PrettyFormat);
    	
    }
}
